package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.result.Result;
import com.itheima.mapper.SysMenuMapper;
import com.itheima.pojo.SysMenu;
import com.itheima.service.SysMenuService;
import com.itheima.vo.SysMenuVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService  {


    /**
     * 所有菜单
     *
     * @return
     */
    @Override
    public Result menuList() {
        LambdaQueryWrapper<SysMenu> qw1  = new LambdaQueryWrapper();
        qw1.eq(SysMenu::getPid,0);
        List<SysMenu> list = list(qw1);
        List<SysMenuVo> list1 = listVo(list);

        return Result.success(list1);
    }

    /**
     * 通过id查询详细菜单
     *
     * @param id
     * @return
     */
    @Override
    public Result rowInfo(Integer id) {
        SysMenu byId = getById(id);
        return Result.success(byId);
    }

    /**
     * 修改菜单
     *
     * @param sysMenu
     * @return
     */
    @Override
    public Result menuUpdate(SysMenu sysMenu) {
        updateById(sysMenu);
        return Result.success();
    }

    /**
     * 添加菜单
     *
     * @param sysMenu
     * @return
     */
    @Override
    public Result menuAdd(SysMenu sysMenu) {
        save(sysMenu);
        return Result.success();
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
        removeById(id);
        return Result.success();
    }

    public List<SysMenuVo> listVo(List<SysMenu> list){
        List<SysMenuVo> listvo = new ArrayList<>();
        list.forEach(s->{
            SysMenuVo sysMenuVo = new SysMenuVo();
            BeanUtils.copyProperties(s,sysMenuVo);
            LambdaQueryWrapper<SysMenu> qw  = new LambdaQueryWrapper();
            qw.eq(SysMenu::getPid,s.getId());
            List<SysMenu> list1 = list(qw);
            if(list1.size()==0){
                listvo.add(sysMenuVo);
                return;
            }
            sysMenuVo.setChildren(listVo(list1));
            listvo.add(sysMenuVo);
        });
        return listvo;
    }
}
